<template>
  <div class="pad-content-box form-no-padding-box padding-top-20">
    <el-form size="small" label-width="125px" :model="searchParams">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="收款批号">
            <el-input v-model="searchParams.collectionBatchNo" clearable placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收款公司">
            <el-input v-model="searchParams.gongsi" clearable placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资产简码">
            <el-select v-model="searchParams.chargeItemCodes" clearable filterable>
              <el-option v-for="item in options.assetList" :key="item.shopCode" :label="item.shopNumber" :value="item.shopCode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="品牌">
            <el-select v-model="searchParams.operateBrandList" clearable filterable multiple>
              <el-option v-for="item in options.brandList" :key="item.primaryKey" :label="item.catalogName" :value="item.primaryKey" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="费项名称">
            <el-select v-model="searchParams.bizType" clearable filterable>
              <el-option v-for="item in options.chargeList" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退款账户">
            <el-input v-model="searchParams.partnerAId" clearable placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收款开始时间">
            <el-date-picker v-model="searchParams.cycleStartTime" type="date" value-format="timestamp" :picker-options="pickerOptionsStart" clearable placeholder="请选择"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收款结束时间">
            <el-date-picker v-model="searchParams.cycleEndTime" type="date" value-format="timestamp" :picker-options="pickerOptions" clearable placeholder="请选择"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同编号">
            <el-select v-model="searchParams.likeContractCode" clearable filterable>
              <el-option v-for="item in options.contractList" :key="item.contractCode" :label="item.contractCode" :value="item.contractCode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退款开始时间">
            <el-date-picker v-model="searchParams.gereturndate" type="date" value-format="timestamp" :picker-options="pickerRefundOptionsStart" clearable placeholder="请选择"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退款结束时间">
            <el-date-picker v-model="searchParams.lereturndate" type="date" value-format="timestamp" :picker-options="pickerRefundOptions" clearable placeholder="请选择"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退款批次">
            <el-input v-model="searchParams.returnBatchNo" clearable placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-button type="primary" size="small" class="f-right" @click="getList('')">查询</el-button>
        <el-button type="primary" size="small" class="f-right margin-right-10" @click="returnSaleReport">返还</el-button>
        <el-button type="primary" size="small" class="f-right" @click="deductionSaleReport">抵扣</el-button>
        <el-button type="primary" size="small" class="f-right" @click="addSaleReport">收款</el-button>
        <el-button type="primary" size="small" class="f-right" @click="exportFn">Excel导出</el-button>
      </el-col>
    </el-form>

    <el-table class="margin-top-20 has-tab-header-border new-table-style bold-scrollbar-table" ref="multipleTable" :row-key="getRowKeys" align="left" @selection-change="handleSelectionChange" :data="tableData">
      <el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>
      <el-table-column align="left" label="合同" prop="contractDesc" width="200">
        <template slot-scope="scope">
          <el-link :underline="false" @click="goContractInfo(scope.row)">{{ scope.row.contractDesc }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="left" label="账单说明" width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.customerName">{{ scope.row.customerName }}</span>
          <span v-if="scope.row.operateBrandName">、{{ scope.row.operateBrandName }}</span>
          <span><br />({{ scope.row.chargeItemCode }}：{{ scope.row.assetTypeName }})</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="费项名称" class-name="no-padding" prop="bizTypeName" min-width="120"></el-table-column>
      <el-table-column label="计费开始日期" width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.cycleStartTime | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计费结束日期" width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.cycleEndTime | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应缴费日期" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.paymentDeadline | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应缴费金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.amountReceivable | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="收款日期" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.collectionTime | formatDateTime('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="收款剩余金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.amountReceived | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款批号" prop="collectionBatchNo" min-width="120"> </el-table-column>
      <el-table-column align="center" label="未结金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.unPaymentAmount | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="抵扣金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.deductAmount | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="退款金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.returnAmount | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款批次" prop="returnBatchNo" min-width="120"> </el-table-column>
      <el-table-column align="center" label="备注" class-name="no-padding" min-width="120" prop="billDesc"></el-table-column>
    </el-table>
    <Pagination v-if="total" @change="pageChange" :total="total" paginationLayout="total, prev, pager, next" />
    <el-dialog :visible.sync="showAddDialog" title="押金收款" width="90%" :close-on-click-modal="false" :close-on-press-escape="false">
      <depositCollection @closeDialog="closeDialog" :checkList="checkList" ref="depositCollection" :options="options" @refresh="getList('')"></depositCollection>
    </el-dialog>
    <!-- 押金抵扣 -->
    <deduction ref="deduction" @confirmDeduction="refresh"></deduction>
    <!-- 押金返还 -->
    <bill-refund ref="billRefund" @confirmBillRefund="refresh" :checkList="checkList" :options="options" pageType="cashPledge"></bill-refund>
  </div>
</template>

<script>
  import { apiBillList, apiContractList, apiClientList, apiBillExport } from '../../api/billManage';
  import { apiDepositExport } from '../../api/depositManage';
  import { apiAssetCodeList, apiCategoryList } from '../../api/gatherManage';
  import { apiPactConstant } from '@a/index';
  import depositCollection from './modules/depositCollection.vue';
  import deduction from './modules/deduction.vue';
  import billRefund from '../billManage/components/billRefund.vue';
  import { accSubtr } from '@/common/js/utils.js';

  export default {
    name: 'salesReport',
    components: { depositCollection, deduction, billRefund },
    data() {
      return {
        accSubtr: accSubtr,
        searchParams: {},
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        showAddDialog: false,
        showReturnDialog: false,
        checkList: [],
        options: {
          assetList: [],
          brandList: [],
          chargeList: [],
          contractList: [],
          paymentMethodList: [],
          chargeCashPledgeList: [],
          clientList: [],
        },
        projectKey: localStorage.getItem('projectKey'),
        pickerOptions: {
          disabledDate: time => {
            if (this.searchParams.shoukuankaishishijian) {
              return time.getTime() < this.searchParams.shoukuankaishishijian;
            }
          },
        },
        pickerOptionsStart: {
          disabledDate: time => {
            if (this.searchParams.shoukuankaishishijian) {
              return time.getTime() > this.searchParams.shoukuankaishishijian;
            }
          },
        },
        pickerRefundOptions: {
          disabledDate: time => {
            if (this.searchParams.gereturndate) {
              return time.getTime() < this.searchParams.gereturndate;
            }
          },
        },
        pickerRefundOptionsStart: {
          disabledDate: time => {
            if (this.searchParams.lereturndate) {
              return time.getTime() > this.searchParams.lereturndate;
            }
          },
        },
      };
    },
    mounted() {
      this.getConstant();
      this.getClientList();
      this.getAssetCodeList();
      this.getOperateBrand();
      this.getContractList();
      this.getList();
    },
    methods: {
      async getList(more) {
        let res = await apiBillList({
          currentPage: more ? this.currentPage : 1,
          pageSize: this.pageSize,
          ifDepositBillManagement: true,
          ...this.searchParams,
        });
        res.rows.forEach(item => {
          let nowTime = new Date().getTime();
          let payTime = new Date(item.paymentDeadline).getTime();
          let diffTime = nowTime - payTime;
          let diffDays = Math.floor(diffTime / (1000 * 3600 * 24));
          diffDays = Math.abs(diffDays);
          if (nowTime > payTime) {
            item.isOverdue = true;
            item.statusName = '逾期' + diffDays + '天';
          } else {
            item.statusName = '距离缴费日期' + diffDays + '天';
          }
        });
        this.tableData = res.rows || [];
        this.total = res.total || 0;
      },

      //常量
      async getConstant() {
        let res = await apiPactConstant();
        this.options.chargeList = res.billType || [];
        this.options.paymentMethodList = res.actualIncomePaymentMethod || [];
        this.options.chargeCashPledgeList = res.billTypeDeposit || [];
      },

      //资产codelist
      async getAssetCodeList() {
        let res = await apiAssetCodeList({
          projectKeys: [this.projectKey],
        });
        this.options.assetList = res.rows || [];
      },

      //品牌
      async getOperateBrand() {
        let res = await apiCategoryList({
          catalogTypeList: ['brand_child'],
        });
        this.options.brandList = res.rows || [];
      },

      //选择客户数据源
      async getClientList() {
        let res = await apiClientList();
        this.options.clientList = res.rows || []
      },

      //选择合同数据源
      async getContractList() {
        let res = await apiContractList({ projectKey: this.projectKey });
        this.options.contractList = res.rows || [];
      },

      //分页
      pageChange(page) {
        this.currentPage = page.currentPage;
        this.getList('more');
      },

      //复选框选择
      handleSelectionChange(list) {
        this.checkList = this.lodash.cloneDeep(list);
      },

      refresh() {
        this.checkList = [];
        this.$refs.multipleTable.clearSelection();
        this.getList('');
      },

      //收款
      async addSaleReport() {
        let customerKeysList = this.checkList.map(item => {
          return item.customerKeys;
        });
        let len = Array.from(new Set(customerKeysList)).length;
        if (len > 1) {
          this.$message.warning('请选择相同客户的账单！');
          return;
        }
        this.showAddDialog = true;
        await this.$nextTick(() => {});
        this.$refs.depositCollection.init();
      },

      //返还
      async returnSaleReport() {
        if (!this.isEmptyCheckList()) return;
        if (this.checkList.length > 1) {
          this.$message.warning('返还账单至多选择一条！');
          return;
        }
        this.$refs.billRefund.init();
      },
      
      //抵扣
      deductionSaleReport() {
        this.$refs.deduction.init();
      },

      //合同详情
      goContractInfo(row) {
        let param = {
          contractType: row.contractType,
          contractCode: row.contractCode,
          contractKey: row.contractKey,
          contractCategory: row.contractCategory,
          headerName: '合同管理',
          showApprove: 'no',
        };

        let pathName = '/businessAssets/ContractManage/info?';
        for (let i in param) {
          pathName += i + '=' + param[i] + '&';
        }
        window.open(pathName);
      },

      closeDialog() {
        this.showAddDialog = false;
      },

      //导出
      async exportFn() {
        let res = await apiBillExport({
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          ifDepositBillManagement: true,
          ...this.searchParams,
        });
        if (res.success) {
          window.location.href = res.url;
        } else {
          this.$message.warning(res.message);
        }
      },

      //table唯一key
      getRowKeys(row) {
        return row.primaryKey;
      },

      //判断是否选择账单
      isEmptyCheckList() {
        if (this.checkList == 0) {
          this.$message.warning('请选择账单！');
          return false;
        }
        return true;
      },
    },
  };
</script>

<style lang="scss" scoped>
  ::v-deep .has-tab-header-border .el-tabs__header {
    border: none;
  }
  ::v-deep .cell {
    text-align: center;
  }
</style>
